import 'package:flutter/material.dart';
import 'package:linphone_flutter/linphone_chat_message.dart';
import 'package:linphone_flutter_example/phone_view_model.dart';
import 'package:provider/provider.dart';

class ChatView extends StatefulWidget {
  const ChatView({super.key});

  @override
  State<ChatView> createState() => _ChatViewState();
}

class _ChatViewState extends State<ChatView> {
  var remoteSipUri = TextEditingController();
  var messageText = TextEditingController();
  var formKey = GlobalKey();

  @override
  void initState() {
    remoteSipUri.text = "sip:8091@115.29.8.204:5678";
    messageText.text = "test";
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: formKey,
      child: Scaffold(
          appBar: AppBar(
            bottom: PreferredSize(
              preferredSize: const Size(double.infinity, 30),
              child: TextField(
                  decoration: InputDecoration(
                      hintText: "Remote SIP address"),
                  controller: remoteSipUri),
            ),
          ),
          body: Column(
              children: context.watch<PhoneViewModel>().messages.map((LinphoneChatMessage m) {
            return Container(
                color: messageBgColor(m),
                child:Text(m.message!));
          }).toList()),
          bottomSheet: Row(children: [
            Expanded(child: TextField(
              decoration: InputDecoration(hintText: "Text"),
              controller: messageText,
            )),
            MaterialButton(onPressed: send, child: Text("SEND MESSAGE"))
          ])),
    );

  }

  messageBgColor(LinphoneChatMessage m){
    switch(m.messageState){
      case MessageState.InProgress:
        return Colors.yellow;
        break;
      case MessageState.Delivered:
        return Colors.green;
        break;
      case MessageState.NotDelivered:
        return Colors.red;
        break;
      default:
        return Colors.white;
        break;
    }
  }
  send() {
    FormState formState = formKey.currentState as FormState;
    formState.save();
    context
        .read<PhoneViewModel>()
        .sendMessage(remoteSipUri.text, messageText.text);
  }
}
